package com.jiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiang.dto.Result;
import com.jiang.dto.UserDTO;
import com.jiang.entity.Follow;
import com.jiang.mapper.FollowMapper;
import com.jiang.service.IFollowService;
import com.jiang.service.IUserService;
import com.jiang.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiang
 * @since 2024-3-20
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 1、获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;

        // 2、判断到底是关注还是取关
        if (isFollow) {
            // 3、关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            boolean isSuccess = save(follow);
            if (isSuccess) {
                // 把关注用户的id，放入redis的set集合 sadd userId followerUserId
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            // 4、取关，删除
            boolean isSuccess = remove(new LambdaQueryWrapper<Follow>()
                    .eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId));
            // 把关注用户的id从Redis集合中移除
            if (isSuccess) {
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        // 1、获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 2、查询是否关注
        Integer count = lambdaQuery().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId).count();
        // 判断
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(Long followUserId) {
        // 1、获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 2、求交集
        String userKey = "follows:" + userId;
        String followKey = "follows:" + followUserId;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(userKey, followKey);
        // 3、继续id集合
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> list = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4、查询用户
        List<UserDTO> userDTOS = userService.listByIds(list)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
